<!-- jquery-ui -->
<script src="/static/plugins/jquery-ui.min.js"></script>

<!-- d3.js -->
<script src="/static/plugins/d3/d3.min.js"></script>
<!-- datepicker -->
<script src="/static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
<script src="/static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script>

<!-- nicescroll -->
<script src="/static/plugins/jquery.nicescroll/jquery.nicescroll.min.js"></script>

<script src="/static/plugins/skycons/skycons.js"></script>
<script src="/static/plugins/jquery-knob/js/jquery.knob.js"></script>

<!-- echart -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=Bp7u5buCk50MW9vp9ufmnFD34d2z2KBH&s=1"></script>
<script type="text/javascript" src="/static/plugins/echarts/echarts.min.js"></script>
<script src="/static/plugins/echarts/theme/macarons.js"></script>
<!-- 引入百度地图扩展 -->
<script src="/static/plugins/echarts/extension/bmap/bmap.min.js"></script>
<script src="/static/product/scripts/hashmap.js"></script>

<script>
    var collectCountOfMonthChart = echarts.init(document.getElementById('collectCountOfMonth'));
    var overviewTodayChart = echarts.init(document.getElementById('overviewTodayChart'), 'macarons');
    var myChart = echarts.init(document.getElementById('world-map-gdp'));

    $(function () {
        pageInit();
    });

    function pageInit() {
        loadMoveContainer();
        loadDatepicker();
        loadSkycons();

        loadCollectCountOfMonth();
        loadOverviewToday(new Date());
        loadOverviewChoice();

        loadTree();
        loadDtuRowToday();
        loadDtuCount();
        loadMonthCollector();
        loadEchartsMap();
        loadWeather();

        $(window).resize(function () {
            collectCountOfMonthChart.resize();
        });
    }

    function loadMoveContainer() {
        // Make the dashboard widgets sortable Using jquery UI
        $('.connectedSortable').sortable({
            placeholder: 'sort-highlight',
            connectWith: '.connectedSortable',
            handle: '.box-header, .nav-tabs',
            forcePlaceholderSize: true,
            zIndex: 99,
            update: function (event, ui) {
                collectCountOfMonthChart.resize();
                overviewTodayChart.resize();
                $('#dtuRowToday').getNiceScroll().resize();
            }
        });
        $('.connectedSortable .box-header, .connectedSortable .nav-tabs').css('cursor', 'move');
    }

    function loadMonthCollector() {
        //jQueryKnob
        $('.knob').knob();
    }

    function loadSkycons(){
        if( typeof (Skycons) === 'undefined'){
            return;
        }

        var icons = new Skycons({"color": "#73879C"});
        var list = ["clear-day",
                    "clear-night",
                    "partly-cloudy-day",
                    "partly-cloudy-night",
                    "cloudy",
                    "rain",
                    "sleet",
                    "snow",
                    "wind",
                    "fog"
                    ],
                    i;
        for (i = list.length; i--;)
            icons.set(list[i], list[i]);

        icons.play();
    }

    function loadDatepicker() {
        // The Calender
        $('#calendar').datepicker({
            language: 'zh-CN',       //语言
            todayHighlight: true    //今天高亮
        });
    }

    //加载地图
    function loadEchartsMap() {
        var url = '{{ urlfor "HomeController.GetCustomerZone"}}';

        $.sdpost(url, {}, function (re) {
            if (re.code === 0) {
                var hq_png = "/static/sdtheme/img/tiger.png";
                var hq_name = '可信电力';
                var hq_ll = [113.350545,23.123564];
                var h_data = [
                    {name: hq_name, value: hq_ll, symbol: 'image://' + hq_png, "symbolSize": 40, "itemStyle":{"normal":{"color":"#F58158"}}}
                ];

                var d_data = [];
                var moveLines = [];
                var ary = new Array('天河区', '海珠区', '白云区', '越秀区', '荔湾区', '黄埔区',
                                     '增城区', '花都区', '从化区', '番禺区', '南沙区', '其它');
                var ary2 = new Array(0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0
                                      );
                var total = 0;
                $(re.obj).each(function (i, row) {
                    var obj = {name: row.CustomerName, value:[row.Longitude , row.Latitude , row.Num]};
                    d_data.push(obj);
                    var obj2 = {fromName: row.CustomerName, toName: hq_name, coords:[[row.Longitude, row.Latitude], hq_ll]};
                    moveLines.push(obj2);

                    switch (row.Zone.trim()){
                        case '天河区': ary2[0]++; break;
                        case '海珠区': ary2[1]++; break;
                        case '白云区': ary2[2]++; break;
                        case '越秀区': ary2[3]++; break;
                        case '荔湾区': ary2[4]++; break;
                        case '黄埔区': ary2[5]++; break;
                        case '增城区': ary2[6]++; break;
                        case '花都区': ary2[7]++; break;
                        case '从化区': ary2[8]++; break;
                        case '番禺区': ary2[9]++; break;
                        case '南沙区': ary2[10]++; break;
                        case '其它'  : ary2[11]++; break;
                        default: break;
                    }
                    total++;
                });

                var html = [];
                ary.map(function (value, index) {
                    var num = ary2[index];
                    var rate = num / total * 100;
                    html.push('<div class="progress-group">');
                    html.push('<span class="progress-text"> ' + value + '</span>');
                    html.push('<span class="progress-number">'+ num +'</span>');
                    html.push('<div class="progress sm">');
                    html.push('<div class="progress-bar progress-bar-aqua" style="width: '+ rate + '%"></div>');
                    html.push('</div>');
                    html.push('</div>');
                });
                $('#customerZone').html(html.join(''));
                $('#customers').html(total);

                var option = {
                    tooltip : {
                        trigger: 'item',
                        // formatter: '  {a}<br>{b}<br> {c}'
                        formatter: function (params) {
                            var res = '';
                            if(params['seriesType'] === 'effectScatter'){
                                res = params['seriesName'] + '<br>' + params['name'] + '<br>' + '电表数量：' + params['value'][2];
                            }else if(params['seriesType'] === 'lines'){
                                res = params.data['fromName'];
                            }
                            return res;
                        }
                    },

                    bmap: {
                        center: [113.329147, 23.115899],   // 中心位置坐标
                        zoom: 11,                          // 地图缩放比例
                        roam: true                        // 开启用户缩放
                    },
                    series : [
                        {
                            name: '总部',
                            type: 'scatter',
                            coordinateSystem: 'bmap',
                            zlevel: 2,
                            rippleEffect: {
                                brushType: 'stroke',
                                period:7,
                                scale:26
                            },
                            label: {
                                normal: {
                                    show: true,
                                    position: 'top',
                                    formatter: '{b}',
                                    color: '#ff0000'
                                }
                            },
                            symbolSize: 2,
                            showEffectOn: 'render',
                            itemStyle: {
                                normal: {
                                    color: '#46bee9'
                                }
                            },
                            data: h_data
                        },

                        {
                            name: '客户',
                            type: 'effectScatter',
                            coordinateSystem: 'bmap',
                            data: d_data,
                            symbolSize: function (val) {
                                return val[2] < 5 ? 10 : val[2];
                            },
                            showEffectOn: 'render',
                            rippleEffect: {
                                brushType: 'stroke'
                            },
                            hoverAnimation: true,

                            itemStyle: {
                                normal: {
                                    color: '#00c0ef',
                                    shadowBlur: 10,
                                    shadowColor: '#0ff'
                                }
                            },
                            zlevel: 1
                        },

                        {
                            name: '线路',
                            type: 'lines',
                            coordinateSystem: 'bmap',
                            zlevel: 2,
                            large: true,
                            effect: {
                                show: true,
                                constantSpeed: 30,
                                symbol: 'arrow',//ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
                                symbolSize: 6,
                                trailLength: 0
                            },
                            lineStyle: {
                                normal: {
                                    color: '#0ff',
                                    width: 2,
                                    opacity: 0.6,
                                    curveness: 0.1
                                }
                            },
                            data: moveLines
                        }
                    ]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);

                // 添加百度地图插件
                var bmap = myChart.getModel().getComponent('bmap').getBMap();
                bmap.addControl(new BMap.ScaleControl());         //比例尺
                bmap.addControl(new BMap.NavigationControl());    //缩放控件
                bmap.addControl(new BMap.MapTypeControl());       //地图类型控件
                bmap.addControl(new BMap.OverviewMapControl({isOpen: true, anchor:BMAP_ANCHOR_BOTTOM_RIGHT}));   //缩略地图控件

                $("#world-map-gdp").resize(function () {
                    var h = $(".box.maximized-box .box-body").height();
                    if(h === null)
                        h = 360;
                    $("#world-map-gdp").height(h);
                    myChart.resize();
                });
            } else {
                layer.alert("加载地图失败", {icon: 2, title: '错误'})
            }
        });
    }

    //设备安装信息
    //http://www.robschmuecker.com/d3-js-drag-and-drop-zoomable-tree/
    function loadTree() {
        var url = '{{ urlfor "HomeController.GetCustomerForMeter"}}';

        d3.json(url, function(error, re) {
            if(re.code != 0) throw error;

            // Define the root
            var root = JSON.parse(re.obj);

            // Calculate total nodes, max label length
            var totalNodes = 0;
            var maxLabelLength = 0;

            // variables for drag/drop
            var selectedNode = null;
            var draggingNode = null;

            // Misc. variables
            var i = 0;
            var duration = 750;

            // size of the diagram
            var viewerWidth = $("#tree-container").width();
            var viewerHeight = $("#tree-container").height() == 0 ? 300 : $("#tree-container").height();

            var tree = d3.layout.tree().size([viewerHeight, viewerWidth]);

            // define a d3 diagonal projection for use by the node paths later on.
            var diagonal = d3.svg.diagonal()
                    .projection(function(d) {
                        return [d.y, d.x];
                    });

            // A recursive helper function for performing some setup by walking through all nodes
            function visit(parent, visitFn, childrenFn) {
                if (!parent) return;

                visitFn(parent);

                var children = childrenFn(parent);
                if (children) {
                    var count = children.length;
                    for (var i = 0; i < count; i++) {
                        visit(children[i], visitFn, childrenFn);
                    }
                }
            }
            // Call visit function to establish maxLabelLength
            visit(root, function(d) {
                totalNodes++;
                maxLabelLength = Math.max(d.name.length, maxLabelLength);
            }, function(d) {
                return d.children && d.children.length > 0 ? d.children : null;
            });

            // sort the tree according to the node names
            function sortTree() {
                tree.sort(function(a, b) {
                    return b.name.toLowerCase() < a.name.toLowerCase() ? 1 : -1;
                });
            }
            // Sort the tree initially incase the JSON isn't in a sorted order.
            sortTree();

            // Define the zoom function for the zoomable tree
            function zoom() {
                svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
            }

            // define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
            var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom);

            // define the baseSvg, attaching a class for styling and the zoomListener
            var baseSvg = d3.select("#tree-container")
                            .append("svg")
                            .attr("width", viewerWidth)
                            .attr("height", viewerHeight)
                            .attr("class", "overlay")
                            .call(zoomListener);

            var overCircle = function(d) {
                selectedNode = d;
                updateTempConnector();
            };

            var outCircle = function(d) {
                selectedNode = null;
                updateTempConnector();
            };

            // Function to update the temporary connector indicating dragging affiliation
            var updateTempConnector = function() {
                var data = [];
                if (draggingNode !== null && selectedNode !== null) {
                    // have to flip the source coordinates since we did this for the existing connectors on the original tree
                    data = [{
                        source: {
                            x: selectedNode.y0,
                            y: selectedNode.x0
                        },
                        target: {
                            x: draggingNode.y0,
                            y: draggingNode.x0
                        }
                    }];
                }
                var link = svgGroup.selectAll(".templink").data(data);

                link.enter().append("path")
                        .attr("class", "templink")
                        .attr("d", d3.svg.diagonal())
                        .attr('pointer-events', 'none');

                link.attr("d", d3.svg.diagonal());

                link.exit().remove();
            };

            // Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
            function centerNode(source) {
                scale = zoomListener.scale();
                x = 80;
                y = -source.x0;
                y = y * scale + viewerHeight / 2;

                d3.select('g').transition()
                        .duration(duration)
                        .attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
                zoomListener.scale(scale);
                zoomListener.translate([x, y]);
            }

            // Toggle children function
            function toggleChildren(d) {
                if (d.children) {
                    d._children = d.children;
                    d.children = null;
                } else if (d._children) {
                    d.children = d._children;
                    d._children = null;
                }
                return d;
            }

            // Toggle children on click.
            function click(d) {
                if (d3.event.defaultPrevented) return; // click suppressed
                d = toggleChildren(d);
                update(d);
                centerNode(d);
            }

            function update(source) {
                // Compute the new height, function counts total children of root node and sets tree height accordingly.
                // This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
                // This makes the layout more consistent.
                var levelWidth = [1];
                var childCount = function(level, n) {
                    if (n.children && n.children.length > 0) {
                        if (levelWidth.length <= level + 1)
                            levelWidth.push(0);

                        levelWidth[level + 1] += n.children.length;
                        n.children.forEach(function(d) {
                            childCount(level + 1, d);
                        });
                    }
                };

                childCount(0, root);
                var newHeight = d3.max(levelWidth) * 25; // 25 pixels per line
                tree = tree.size([newHeight, viewerWidth]);

                // Compute the new tree layout.
                var nodes = tree.nodes(root).reverse(),
                        links = tree.links(nodes);

                // Set widths between levels based on maxLabelLength.
                nodes.forEach(function(d) {
                    d.y = (d.depth * (maxLabelLength * 10)); //maxLabelLength * 10px
                    // alternatively to keep a fixed scale one can set a fixed depth per level
                    // Normalize for fixed-depth by commenting out below line
                    // d.y = (d.depth * 500); //500px per level.
                });

                // Update the nodes…
                node = svgGroup.selectAll("g.node")
                        .data(nodes, function(d) {
                            return d.id || (d.id = ++i);
                        });

                // Enter any new nodes at the parent's previous position.
                var nodeEnter = node.enter().append("g")
                        .attr("class", "node")
                        .attr("transform", function(d) {
                            return "translate(" + source.y0 + "," + source.x0 + ")";
                        })
                        .on('click', click);

                nodeEnter.append("circle")
                        .attr('class', 'nodeCircle')
                        .attr("r", 0)
                        .style("fill", function(d) {
                            return d._children ? "lightsteelblue" : "#fff";
                        });

                nodeEnter.append("text")
                        .attr("x", function(d) {
                            return d.children || d._children ? -10 : 10;
                        })
                        .attr("dy", ".35em")
                        .attr('class', 'nodeText')
                        .attr("text-anchor", function(d) {
                            return d.children || d._children ? "end" : "start";
                        })
                        .text(function(d) {
                            return d.children || d._children ? d.name : d.name + ": " + d.desc;
                        })
                        .style("fill-opacity", 0);

                // phantom node to give us mouseover in a radius around it
                nodeEnter.append("circle")
                        .attr('class', 'ghostCircle')
                        .attr("r", 30)
                        .attr("opacity", 0.2) // change this to zero to hide the target area
                        .style("fill", "red")
                        .attr('pointer-events', 'mouseover')
                        .on("mouseover", function(node) {
                            overCircle(node);
                        })
                        .on("mouseout", function(node) {
                            outCircle(node);
                        });

                // Update the text to reflect whether node has children or not.
                node.select('text')
                        .attr("x", function(d) {
                            return d.children || d._children ? -10 : 10;
                        })
                        .attr("text-anchor", function(d) {
                            return d.children || d._children ? "end" : "start";
                        })
                        .text(function(d) {
                            return d.children || d._children ? d.name : d.name + ": " + d.desc;
                        });

                // Change the circle fill depending on whether it has children and is collapsed
                node.select("circle.nodeCircle")
                        .attr("r", 4.5)
                        .style("fill", function(d) {
                            return d._children ? "lightsteelblue" : "#fff";
                        });

                // Transition nodes to their new position.
                var nodeUpdate = node.transition()
                        .duration(duration)
                        .attr("transform", function(d) {
                            return "translate(" + d.y + "," + d.x + ")";
                        });

                // Fade the text in
                nodeUpdate.select("text").style("fill-opacity", 1);

                // Transition exiting nodes to the parent's new position.
                var nodeExit = node.exit().transition()
                        .duration(duration)
                        .attr("transform", function(d) {
                            return "translate(" + source.y + "," + source.x + ")";
                        })
                        .remove();

                nodeExit.select("circle").attr("r", 0);

                nodeExit.select("text").style("fill-opacity", 0);

                // Update the links…
                var link = svgGroup.selectAll("path.link")
                        .data(links, function(d) {
                            return d.target.id;
                        });

                // Enter any new links at the parent's previous position.
                link.enter().insert("path", "g")
                        .attr("class", "link")
                        .attr("d", function(d) {
                            var o = {
                                x: source.x0,
                                y: source.y0
                            };

                            return diagonal({
                                source: o,
                                target: o
                            });
                        });

                // Transition links to their new position.
                link.transition()
                        .duration(duration)
                        .attr("d", diagonal);

                // Transition exiting nodes to the parent's new position.
                link.exit().transition()
                        .duration(duration)
                        .attr("d", function(d) {
                            var o = {
                                x: source.x,
                                y: source.y
                            };
                            return diagonal({
                                source: o,
                                target: o
                            });
                        })
                        .remove();

                // Stash the old positions for transition.
                nodes.forEach(function(d) {
                    d.x0 = d.x;
                    d.y0 = d.y;
                });
            }

            // Append a group which holds all nodes and which the zoom Listener can act upon.
            var svgGroup = baseSvg.append("g");

            // Layout the tree initially and center on the root node.
            root.x0 = 0;
            root.y0 = 0;

            update(root);
            centerNode(root);
        });

        $('#tree-container').resize(function () {
            var h = $(".box.maximized-box .box-body").height();
            if(h === null)
                h = 300;
            $("#tree-container .overlay").height(h);
        });
    }

    //网络设备数量
    function loadDtuCount() {
        var url = '{{ urlfor "HomeController.GetDtuCount"}}';
        $.sdpost(url, {}, function (re) {
            if (re.code === 0) {
                $("#dtuCount").html(re.obj);
            } else {
                layer.alert("网络设备数量数据获取失败", {icon: 2, title: '错误'})
            }
        });
    }

    function getNowRows() {
        var datetime = new Date();
        return Math.round((datetime.getHours() * 60 + datetime.getMinutes()) / 5);
    }

    //今日设备状态
    function loadDtuRowToday() {
        var url = '{{ urlfor "HomeController.GetDtuRowForDay"}}';
        $.sdpost(url, {}, function (re) {
            if (re.code === 0) {
                var html = [], html2 = [];
                //datastateary[0]  dtuOnline
                //datastateary[1]  dtuOffline
                //datastateary[2]  dtuNormal
                //datastateary[3]  dtuAbnormal
                var datastateary = new Array(0,0,0,0);

                $(re.obj).each(function (i, row) {
                    if(row.Rows === 0){
                        datastateary[1]++;

                        html2.push('<tr>');
                        html2.push(' <td>' + datastateary[1]  + '</td>  <td>' + row.DTU_no  + '</td> <td>' + row.MeterAddress  + '</td>');
                        html2.push('</tr>');
                    }else{
                        datastateary[0]++;

                        html.push('<div class="progress-group">');
                        html.push('<span class="progress-text">' + row.DTU_no + " & " + row.MeterAddress+ '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                        html.push('<i class="fa fa-clock-o"></i>');
                        html.push(' <small>'+ sdtheme.formatterDateTimeBySpan(row.CollectTime) +'</small>');
                        html.push('<span class="progress-number"><b>' + row.Rows + '</b>/' + row.DayRows + '</span>');
                        html.push('<div class="progress sm">');

                        var rate = Math.round((row.Rows / row.DayRows) * 10000) / 100;
                        var maxValue = getNowRows();
                        if(row.Rows  < (maxValue * 0.60 )) {
                            html.push('<div class="progress-bar progress-bar-red" style="width:' + rate + '%"></div>');
                            datastateary[3]++;
                        } else if(row.Rows < (maxValue * 0.95 )){
                            html.push('<div class="progress-bar progress-bar-yellow" style="width:' + rate + '%"></div>');
                            datastateary[3]++;
                        } else {
                            html.push('<div class="progress-bar progress-bar-aqua" style="width:' + rate + '%"></div>');
                            datastateary[2]++;
                        }
                        html.push('</div>');
                    }
                });

                var dtuState = '状态(在线:' + datastateary[0] +
                               ' 离线:' + datastateary[1] +
                               ') 数据(正常:' + datastateary[2] +
                               ' 异常:' + datastateary[3] + ')';
                $('#dtuState').html(dtuState);

                $('#meterCount').html(datastateary[0] + datastateary[1]);
                $('#dtuRowToday').html(html.join(''));
                $('#offlineTable').find("tbody").html(html2.join());

                $('#dtuRowToday').height(250);
                $('#dtuRowToday').niceScroll({
                    touchbehavior: true // 激活拖拽滚动
                });
            } else {
                layer.alert("今日设备状态获取失败", {icon: 2, title: '错误'})
            }
        });
    }

    function getLastMonth() {
        var cur = new Date();
        var datetime = cur.setDate(cur.getDate() - 30);
        return sdtheme.formatDate(datetime);
    }

    //月统计
    function loadCollectCountOfMonth() {
        var url = '{{ urlfor "HomeController.GetCollectCountOfMonth"}}';
        $.sdpost(url, {}, function (re) {
            if (re.code === 0) {
                var option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    dataZoom: [
                        {startValue: getLastMonth()},
                        {type: 'inside'}
                    ],
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        top: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: re.obj.map(function (item) {
                            return new Date(item.CollectTime).format("yyyy-MM-dd");
                        }),
                        splitLine: {
                            show: false
                        }
                    },
                    yAxis: {
                        axisLabel: {
                            formatter: function (val) {
                                return val;
                            }
                        },
                        splitLine: {
                            show: true
                        }
                    },
                    series: [ {
                        type: 'line',
                        data: re.obj.map(function (item) {
                            return item.Rows;
                        }),
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        showSymbol: true
                    }]
                };
                collectCountOfMonthChart.setOption(option);
            } else {
                layer.alert("月统计数据获取失败", {icon: 2, title: '错误'})
            }
        });
    }

    //总体概述
    function loadOverviewToday(choiceDate) {
        var url = '{{ urlfor "HomeController.GetOverviewToday"}}';
        var tmp_str = choiceDate.format("yyyy-MM-dd");
        var params = {choiceDate: tmp_str};
        $.sdpost(url, params, function (re) {
            if (re.code === 0) {
                var totalDayRows = 0, totalRows = 0;
                $('#overviewTodayProcess').html('');

                $(re.obj).each(function (i, row) {
                    var html = [];
                    var rate = (row.Rows / row.DayRows * 100).toFixed(2);
                    if (row.TypeID === 1){
                        html.push('<span class="info-box-text">' + row.TypeDesc + '</span>');
                        html.push('<span class="info-box-number">' + row.Rows + '/' + row.DayRows + '</span>');
                        html.push('<div class="progress">');
                        html.push('    <div class="progress-bar" style="width: ' + rate + '%"></div>');
                        html.push('</div>');
                        html.push('<span class="progress-description">已采集：' + rate + '% </span>');

                        switch (row.TypeNO) {
                            case 1000: $('#PMAC600B_Z_SC').html(html.join('')); break;
                            case 1001: $('#LU_312').html(html.join('')); break;
                            case 1002: $('#PMAC720').html(html.join('')); break;
                            case 1004: $('#PD866E').html(html.join('')); break;
                            case 1006: $('#YD2045C_W').html(html.join('')); break;
                            case 1007: $('#PMC-D726M').html(html.join('')); break;
                            case 1009: $('#RJ-OP485').html(html.join('')); break;
                            default: break;
                        }
                    }else if(row.TypeID === 2){
                        html.push('<div class="progress-group">');
                        html.push('  <span class="progress-text"> '+ row.TypeDesc +'</span>');
                        html.push('  <small class="text-green">已采集：' + rate + '% </small>');
                        html.push('  <span class="progress-number"><b>' + row.Rows + '</b>/' + row.DayRows + '</span>');
                        html.push('  <div class="progress sm">');
                        html.push('    <div class="progress-bar progress-bar-aqua" style="width: '+ rate + '%"></div>');
                        html.push('    </div>');
                        html.push('  </div>');
                        html.push('</div>');
                        totalDayRows += row.DayRows;
                        totalRows += row.Rows;

                        $('#overviewTodayProcess').append(html.join(''));
                    }
                });

                var rate = (totalRows / totalDayRows * 100).toFixed(2);
                var html = [];
                html.push('<div class="progress-group">');
                html.push('  <span class="progress-text"> 总采集量</span>');
                html.push('  <small class="text-red">已采集：' + rate + '% </small>');
                html.push('  <span class="progress-number"><b>' + totalRows + '</b>/' + totalDayRows + '</span>');
                html.push('  <div class="progress sm">');
                html.push('    <div class="progress-bar progress-bar-green" style="width: '+ rate + '%"></div>');
                html.push('    </div>');
                html.push('  </div>');
                html.push('</div>');

                $('#rowsToday').html(totalRows);
                $('#overviewTodayProcess').append(html.join(''));

                var option={
                    title:{
                        text: tmp_str,
                        subtext: '监控状态',
                        left: 'right'
                    },

                    tooltip : {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend:{
                        orient: 'vertical',
                        x: 'left',
                        data: re.obj.map(function (item) {
                            return item.TypeDesc;
                        })
                    },
                    series:[
                        {
                            name: '通讯方式',
                            type: 'pie',
                            selectedMode: 'single',
                            radius : [0, 70],

                            // for funnel
                            x: '20%',
                            width: '40%',
                            funnelAlign: 'right',
                            data: re.obj.map(function (item) {
                                if(item.TypeID === 2){
                                    return {value: item.Num, name: item.TypeDesc};
                                }
                            })
                        },{
                            name:'设备类型',
                            type:'pie',
                            selectedMode: 'single',
                            radius : [100, 140],

                            // for funnel
                            x: '60%',
                            width: '35%',
                            funnelAlign: 'left',
                            data: re.obj.map(function (item) {
                                if(item.TypeID === 1){
                                    return {value: item.Num, name: item.TypeDesc};
                                }
                            })
                        }
                    ]
                };
                overviewTodayChart.setOption(option);
            } else {
                layer.alert("总体概述数据获取失败", {icon: 2, title: '错误'})
            }
        });
    }

    //总体概述-日期选择
    function loadOverviewChoice() {
        var curdate = new Date();
        var choiceDate = new Date();

        $('#dateSelect').on('click', 'li', function () {
            var line = $(this).text();
            if(line === '前一天'){
                choiceDate.setDate(choiceDate.getDate() -1);
                loadOverviewToday(choiceDate);
            }else if(line === '后一天'){
                choiceDate.setDate(choiceDate.getDate() + 1);
                if(choiceDate > curdate){
                    choiceDate.setDate(choiceDate.getDate() -1);
                    return;
                }
                loadOverviewToday(choiceDate);
            }else{
                loadOverviewToday(curdate);
            }
        });
    }

    //获取天气
    function loadWeather(){
        var url = '{{ urlfor "HomeController.GetWeather"}}';
        $.sdpost(url, {}, function (re) {
            if (re.code === 0) {
                $("#degress").html(re.obj)
            }
        });
    }

    //监听div大小变化
    (function($, h, c) {
        var a = $([]),
                e = $.resize = $.extend($.resize, {}),
                i,
                k = "setTimeout",
                j = "resize",
                d = j + "-special-event",
                b = "delay",
                f = "throttleWindow";
        e[b] = 250;
        e[f] = true;
        $.event.special[j] = {
            setup: function() {
                if (!e[f] && this[k]) {
                    return false;
                }
                var l = $(this);
                a = a.add(l);
                $.data(this, d, {
                    w: l.width(),
                    h: l.height()
                });
                if (a.length === 1) {
                    g();
                }
            },
            teardown: function() {
                if (!e[f] && this[k]) {
                    return false;
                }
                var l = $(this);
                a = a.not(l);
                l.removeData(d);
                if (!a.length) {
                    clearTimeout(i);
                }
            },
            add: function(l) {
                if (!e[f] && this[k]) {
                    return false;
                }
                var n;
                function m(s, o, p) {
                    var q = $(this),
                            r = $.data(this, d);
                    r.w = o !== c ? o: q.width();
                    r.h = p !== c ? p: q.height();
                    n.apply(this, arguments);
                }
                if ($.isFunction(l)) {
                    n = l;
                    return m;
                } else {
                    n = l.handler;
                    l.handler = m;
                }
            }
        };
        function g() {
            i = h[k](function() {
                        a.each(function() {
                            var n = $(this),
                                    m = n.width(),
                                    l = n.height(),
                                    o = $.data(this, d);
                            if (m !== o.w || l !== o.h) {
                                n.trigger(j, [o.w = m, o.h = l]);
                            }
                        });
                        g();
                    },
                    e[b]);
        }
    })(jQuery, this);
</script>